#include <func.h>

int main(int argc, char* argv[])
{
    // 域名解析服务
    // ./showip 域名
    if (argc != 2) {
        error(1, 0, "Usage: %s 域名", argv[0]);
    }

    struct addrinfo hints;      // 提示
    bzero(&hints, sizeof(hints));   // 先清零
    hints.ai_family = AF_UNSPEC;    // IPv4 or IPv6
    hints.ai_socktype = SOCK_STREAM;    // 流套接字(TCP)
                                        
    struct addrinfo* head;
    int err;
    if ((err = getaddrinfo(argv[1], NULL, &hints, &head)) != 0) {
        fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(err));
        exit(1);
    }

    // 域名解析成功
    // 遍历链表，打印每个地址信息
    struct addrinfo* curr = head;
    char ipstr[40];
    while (curr) {
        char* ip_version;
        void* ip_addr;
        if(curr->ai_family == AF_INET) {
            ip_version = "IPv4";
            struct sockaddr_in* addr = (struct sockaddr_in*) curr->ai_addr;
            ip_addr = &addr->sin_addr;
        } else if (curr->ai_family == AF_INET6){
            // IPv6
            ip_version = "IPv6";
            struct sockaddr_in6* addr = (struct sockaddr_in6*) curr->ai_addr;
            ip_addr = &addr->sin6_addr;
        }

        inet_ntop(curr->ai_family, ip_addr, ipstr, 40);
        printf("%s:%s\n", ip_version, ipstr);

        curr = curr->ai_next;
    }  // curr == NULL

    freeaddrinfo(head);
    return 0;
}

